package com.gxpt.app.view;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

import com.google.gson.Gson;
import com.gxpt.app.AppUtils;
import com.gxpt.app.BaseActivity;
import com.gxpt.app.Constant;
import com.gxpt.app.MessageEvent;
import com.gxpt.app.R;
import com.gxpt.app.bean.normal;
import com.gxpt.app.bean.upload_bean;
import com.utils.ScreenUtils;
import com.utils.T;
import com.utils.logger.Logger;
import com.utils.okhttputils.HttpUtils;
import com.utils.picasso.PicassoUtils;
import com.utils.v24.v_2_4;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

/**
 * Created by dufeng on 2017/8/4.
 */

@ContentView(R.layout.activity_evaluate_goods)
public class Activity_evaluate_goods extends BaseActivity {

    private static final int NONE                 = 0;
    private static final int PHOTO_GRAPH          = 1;// 拍照
    private static final int PHOTO_ZOOM           = 2; // 缩放
    private static final int PHOTO_RESOULT        = 3;// 结果
    private static final String IMAGE_UNSPECIFIED = "image/*";

    String tmppicPath    = "";
    String cropedpicPath = "";

    @ViewInject(R.id.toback)
    Button toback;

    @ViewInject(R.id.txt_title)
    TextView txt_title;

    @ViewInject(R.id.txt_right)
    TextView txt_right;



    @ViewInject(R.id.toPicSel1)
    LinearLayout toPicSel1;

    @ViewInject(R.id.toPicSel2)
    LinearLayout toPicSel2;

    @ViewInject(R.id.toPicSel3)
    LinearLayout toPicSel3;


    @ViewInject(R.id.img_view11)
    ImageView img_view11;

    @ViewInject(R.id.img_view22)
    ImageView img_view22;

    @ViewInject(R.id.img_view33)
    ImageView img_view33;

    @ViewInject(R.id.txt_pic11)
    TextView txt_pic11;

    @ViewInject(R.id.txt_pic22)
    TextView txt_pic22;

    @ViewInject(R.id.txt_pic33)
    TextView txt_pic33;


    @ViewInject(R.id.put_10)
    EditText put_10;

    @ViewInject(R.id.ratingBar)
    RatingBar ratingBar;

    int manner = 5 ;//分数

    //列表图片
    int pic_view_width = 0;
    int pic_view_hight = 0;



    String pic_path1="";
    String pic_path2="";
    String pic_path3="";

    String column_id;

    int index_pic = 1;


    //临时变量
    Uri photoURI;//相加拍摄保存路径
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        x.view().inject(this);

        Bundle b = getIntent().getBundleExtra("DATA");
        if(b!=null){
            column_id = b.getString("column_id");
        }

        int ScreenW  = ScreenUtils.getScreenWidth(context);//
        pic_view_width  = (ScreenW- AppUtils.dip2px(context,5*4))/3;
        pic_view_hight  = pic_view_width;

        initView();



        tmppicPath    = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+"/"+Constant.PRO_DIR+"/"+ Constant.UPLOAD_PIC_TEMP_NAME;
        cropedpicPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+"/"+Constant.PRO_DIR+"/"+Constant.UPLOAD_PIC_CROP_NAME;
    }


    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MessageEvent messageEvent){

    }


    @Override
    public void initView() {
        txt_title.setText(getString(R.string.txt_pingjia));
        txt_right.setVisibility(View.VISIBLE);
        android.view.ViewGroup.LayoutParams lp = toPicSel1.getLayoutParams();
        lp.width  =  pic_view_width;
        lp.height =  pic_view_hight;
        toPicSel1.setLayoutParams(lp);
        toPicSel2.setLayoutParams(lp);
        toPicSel3.setLayoutParams(lp);

        ratingBar.setOnRatingBarChangeListener(new RatingBarListener());

        ratingBar.setRating(5);
    }

    private class RatingBarListener implements RatingBar.OnRatingBarChangeListener{

        public void onRatingChanged(RatingBar ratingBar, float rating,
                                    boolean fromUser) {
            manner = (int)rating;
//            Logger.i("等级：" + manner);
        }
    }



    @Override
    public void initData() {

    }



    @Event(value={R.id.toback,R.id.toPicSel1,R.id.toPicSel2,R.id.toPicSel3,R.id.txt_right})
    private void getEvent(View view){
        switch(view.getId()){
            case R.id.toback:
                closeActivity();
                break;
            case R.id.toPicSel1:
                index_pic = 1;
                Dialog_picsel();
                break;
            case R.id.toPicSel2:
                index_pic = 2;
                Dialog_picsel();
                break;
            case R.id.toPicSel3:
                index_pic = 3;
                Dialog_picsel();
                break;
            case R.id.txt_right:
                if(put_10.getText().toString().equals("")){
                    T.show(context,getResources().getString(R.string.alert_putisnotnull),1);
                }else{
                    toNet_evaluate();
                }
                break;
        }
    }


    public void Dialog_picsel(){
        final Dialog dialog=new Dialog(context,R.style.customDialogStyle);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        View view= LayoutInflater.from(context).inflate(R.layout.dialog_pic_sel, null);
        dialog.setContentView(view);
        view.findViewById(R.id.bt1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CheckPerission_CAMERA();
                dialog.dismiss();
            }
        });

        view.findViewById(R.id.bt2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_UNSPECIFIED);
                startActivityForResult(intent, PHOTO_ZOOM);
                dialog.dismiss();
            }
        });

        view.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        Window dialogWindow = dialog.getWindow();
        dialogWindow.setWindowAnimations(R.style.commonAnimDialogStyle);
        dialogWindow.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        dialogWindow.setGravity(Gravity.BOTTOM);
        dialog.show();

    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == NONE)
            return;
        // 拍照
        if (requestCode == PHOTO_GRAPH) {
            startPhotoZoom(photoURI);
        }

        if (data == null)
            return;

        // 读取相册缩放图片
        if (requestCode == PHOTO_ZOOM) {
            startPhotoZoom(data.getData());
        }

        // 处理结果
        if (requestCode == PHOTO_RESOULT) {
            Bundle extras = data.getExtras();
            if (extras != null) {
                Bitmap photo = extras.getParcelable("data");
                saveCropedPhoto(photo);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    ////////////////////////////////////////////////////////////////////////////////////剪裁图片
    /**
     * 收缩图片
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");//调用Android系统自带的一个图片剪裁页面,
        intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
        intent.putExtra("crop", "false");//进行修剪
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 5);
        intent.putExtra("aspectY", 5);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 200);
        intent.putExtra("outputY",200);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, PHOTO_RESOULT);
    }

    ////////////////////////////////////////////////////////////////////////////////////保存剪裁后的图片
    private void saveCropedPhoto(Bitmap bmp){
        try{
//            String cropedpicPath = this.cropedpicPath;
            File fImage = new File(this.cropedpicPath);
            fImage.createNewFile();
            FileOutputStream iStream = new FileOutputStream(fImage);
            bmp.compress(Bitmap.CompressFormat.PNG, 100, iStream);
            iStream.close();
            iStream =null;
            fImage =null;
            toNet_pic();

        }catch (Exception e){
            Logger.i("error...");
            e.printStackTrace();
        }

    }


    /**
     * 检测权限
     */
    private void CheckPerission_CAMERA() {

        if (Build.VERSION.SDK_INT >= 23){
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA);
//            Logger.i("showCameraAction = "  +checkCallPhonePermission);
            if(checkCallPhonePermission != PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions(Activity_evaluate_goods.this,new String[]{Manifest.permission.CAMERA},Constant.REQUEST_TAKE_CAMERA_PERMISSION);
                return;
            }else{
                CheckPerission_STORAGE();
            }
        }else{
            CheckPerission_STORAGE();
        }
    }

    /**
     * 检测权限
     */
    private void CheckPerission_STORAGE() {
        if (Build.VERSION.SDK_INT >= 23){
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
//            Logger.i("writeSTORAGEAction = "  +checkCallPhonePermission);
            if(checkCallPhonePermission != PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions(Activity_evaluate_goods.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},Constant.REQUEST_TAKE_STORAGE_PERMISSION);
                return;
            }else{
                createPhoto_path();
            }
        }else{
            createPhoto_path();
        }
    }

    //拍照的代码
    private void createPhoto_path() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                //如果是7.0及以上的系统使用FileProvider的方式创建一个Uri
//                Logger.e("Build.VERSION.SDK_INT >= Build.VERSION_CODES.N");
                photoURI = v_2_4.get24MediaFileUri(context);
            } else {
//                Logger.e("7.0以下使用这种方式创建一个Uri");
                photoURI = v_2_4.getMediaFileUri(context);

            }
//            Logger.e("photoURI.getPath() = "+photoURI.getPath());
            //将Uri传递给系统相机
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, PHOTO_GRAPH);
        }
    }

    ////////////////////////////////////////////////////////////////////////////////////NET_PIC
    public void toNet_pic() {
        hud.show();
        Logger.i("cropedpicPath=="+cropedpicPath);
        File file = new File(this.cropedpicPath);
        if (!file.exists())
        {
            T.show(context, "文件不存在，请修改文件路径", 1);
            return;
        }
        Map<String, String> params = new HashMap<>();
        params.put("type", ""+1);
        Map<String, String> headers = new HashMap<>();

        OkHttpUtils
                .post()
                .addFile("upfile", ""+Constant.UPLOAD_PIC_CROP_NAME, file)//
                .url(Constant.URL_upload_file)//
                .params(params)//
                .headers(headers)//
                .build()//
                .execute(pic_do);
    }
    StringCallback pic_do = new StringCallback(){
        @Override
        public void onError(Call call, Exception e, int i) {
            if(hud.isShowing()){
                hud.dismiss();
            }
            Logger.e(e.getMessage());
        }

        @Override
        public void onResponse(String s, int i) {
            if(hud.isShowing()){
                hud.dismiss();
            }
            Logger.e("图片返回:"+s);
            try{
                upload_bean data = new Gson().fromJson(s, upload_bean.class);
                if(data.state !=1 ){
                    T.show(context,data.msg,0);
                }else{
                    //do

//                    "pics":["upload1", "upload2", "upload3"]

                    switch (index_pic){
                        case 1:
                            pic_path1 = data.data;
                            PicassoUtils.Picasso_displayImage(context,Constant.IP+pic_path1,pic_view_width,pic_view_hight,img_view11);
                            img_view11.setVisibility(View.VISIBLE);
                            txt_pic11.setVisibility(View.GONE);

                            toPicSel2.setVisibility(View.VISIBLE);

                            break;
                        case 2:
                            pic_path2 = data.data;
                            PicassoUtils.Picasso_displayImage(context,Constant.IP+pic_path2,pic_view_width,pic_view_hight,img_view22);
                            img_view22.setVisibility(View.VISIBLE);
                            txt_pic22.setVisibility(View.GONE);

                            toPicSel3.setVisibility(View.VISIBLE);
                            break;
                        case 3:
                            pic_path3 = data.data;
                            PicassoUtils.Picasso_displayImage(context,Constant.IP+pic_path3,pic_view_width,pic_view_hight,img_view33);
                            img_view33.setVisibility(View.VISIBLE);
                            txt_pic33.setVisibility(View.GONE);
                            break;
                    }





                }
            }catch (Exception e){
                Logger.i("图片上传出错");
                e.printStackTrace();
                T.show(context,getResources().getString(R.string.alert_again),0);
            }
        }
    };






    //////NET DO
//    StringCallback do_pubdemand = new StringCallback(){
//
//
//        @Override
//        public void onError(Call call, Exception e, int i) {
//            Logger.e(e.getMessage());
//        }
//
//        @Override
//        public void onResponse(String s, int i) {
//            if(hud.isShowing()){
//                hud.dismiss();
//            }
//            Logger.e(s);
//            try{
//                normal data = new Gson().fromJson(s, normal.class);
//
//                if(data.state !=1 ){
//                    T.show(context,data.msg,0);
//                }else{
//                    T.show(context,getResources().getString(R.string.alert_success_do),1);
//                    closeActivity();
//                }
//            }catch (Exception e){
//                e.printStackTrace();
//                T.show(context,getResources().getString(R.string.alert_again),0);
//            }
//        }
//    };
//
////    /////NET
//    private void toNet_pubdemand(){
//        hud.show();
//          JSONObject jsonBody=new JSONObject();
//        try {
//            jsonBody.put("device_number",         AppUtils.get_device_id(context));
//            jsonBody.put("device_type",           Constant.device_type);
//            jsonBody.put("token",                 AppUtils.get_token(context));
//            jsonBody.put("pageName",             "demand");
//            jsonBody.put("serviceName",          "pubdemand");
//
//            jsonBody.put("member_id",            AppUtils.get_user_id(context));
//
//            jsonBody.put("file_url",             pic_path);
//
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//        Logger.i(jsonBody.toString()+" ==["+Constant.URL_pubdemand+" ]");
//        HttpUtils.http_post_string(Constant.URL_pubdemand,jsonBody.toString(),do_pubdemand);
//    }




    private void toNet_evaluate(){
        hud.show();

        JSONArray pics_array = new JSONArray();
        if(!pic_path1.equals("")){
            pics_array.put(pic_path1);
        }
        if(!pic_path2.equals("")){
            pics_array.put(pic_path2);
        }
        if(!pic_path3.equals("")){
            pics_array.put(pic_path3);
        }


        JSONObject jsonBody=new JSONObject();
        try {
            jsonBody.put("device_number",         AppUtils.get_device_id(context));
            jsonBody.put("device_type",           Constant.device_type);
            jsonBody.put("token",                 AppUtils.get_token(context));
            jsonBody.put("pageName",             "shop");
            jsonBody.put("serviceName",          "evaluate");

            jsonBody.put("member_id",            AppUtils.get_user_id(context));
            jsonBody.put("column_id",             column_id);
            jsonBody.put("content",             put_10.getText().toString());
            jsonBody.put("manner",              manner);
            jsonBody.put("pics",              pics_array);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Logger.i(jsonBody.toString()+" ==["+Constant.URL_evaluate+" ]");
        HttpUtils.http_post_string(Constant.URL_evaluate,jsonBody.toString(),do_evaluate);
    }

    StringCallback do_evaluate = new StringCallback(){


        @Override
        public void onError(Call call, Exception e, int i) {
            Logger.e(e.getMessage());
        }

        @Override
        public void onResponse(String s, int i) {
            if(hud.isShowing()){
                hud.dismiss();
            }
            Logger.e(s);
            try{
                normal data = new Gson().fromJson(s, normal.class);

                if(data.state !=1 ){
                    T.show(context,data.msg,0);
                }else{
                    T.show(context,getResources().getString(R.string.alert_success_do),1);
                    closeActivity();
                }
            }catch (Exception e){
                e.printStackTrace();
                T.show(context,getResources().getString(R.string.alert_again),0);
            }
        }
    };
}
